import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/enum/sex.dart';
import 'package:love_app/model/comment_detailst_model.dart' as CDModel;
import 'package:love_app/model/comment_detailst_model.dart';
import 'package:love_app/pages/community/common_ui/content_ui.dart';
import 'package:love_app/providers/attention_provider.dart';
import 'package:love_app/providers/details_data_provider.dart';
import 'package:love_app/providers/latest_provider.dart';
import 'package:love_app/providers/recommend_provider.dart';
import 'package:love_app/providers/search_provider.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/providers/user_center_provider.dart';
import 'package:love_app/service/comment_details_api.dart';
import 'package:love_app/style/space_header.dart.dart';
import 'package:provider/provider.dart';
import 'package:love_app/model/community_model.dart' as CTYModel;

import 'common_ui/show_community_input.dart';

// 社区文章详情页面
class DetailsPage extends StatefulWidget {
  final int itemId; // 从推荐共享数据里去item数据
  final String providerType;

  const DetailsPage(
      {Key key, @required this.itemId, @required this.providerType})
      : super(key: key);

  @override
  _DetailsPageState createState() => _DetailsPageState();
}

class _DetailsPageState extends State<DetailsPage> {
  dynamic _provider; // 推荐页面共享数据
  ShareProvider _shareProvider; // 全局共享数据
  DeatilsDataProvider _deatilsDataProvider; // 社区页面的文章评论共享数据
  BuildContext _context;
  TextEditingController _commentController; // input控制器
  FocusNode _commentFocusNode1; // 输入法焦点
  Offset _offset; // 点击屏幕位置
  OverlayEntry _overlayEntry; // 悬浮控件
  bool _hasOverlay; // 悬浮控件是否显示
  ScrollController _scrollController; // 滚动条监听控制器
  EasyRefreshController _easyRefreshController; // 加载控制器

  BuildArticleItem itemObject;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    _deatilsDataProvider =
        Provider.of<DeatilsDataProvider>(context, listen: true);
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    if (widget.providerType == 'recommend') {
      _provider = Provider.of<RecommendProvider>(context, listen: false);
    } else if (widget.providerType == 'latest') {
      _provider = Provider.of<LatestProvider>(context, listen: false);
    } else if (widget.providerType == 'attention') {
      _provider = Provider.of<AttentionProvider>(context, listen: false);
    } else if (widget.providerType == 'userCenter') {
      _provider = Provider.of<UserCenterProvider>(context, listen: false);
    } else if (widget.providerType == 'searchProvider') {
      _provider = Provider.of<SearchProvider>(context, listen: false);
    }
    if (_deatilsDataProvider.itemId != widget.itemId) {
      _deatilsDataProvider.clean();
      _deatilsDataProvider.itemId = widget.itemId;
      _deatilsDataProvider.isFirst = true;
    }
    // _deatilsDataProvider.hasData(widget.itemId);
  }

  @override
  void initState() {
    super.initState();
    _commentController = TextEditingController();
    _easyRefreshController = EasyRefreshController();
    _commentFocusNode1 = FocusNode();
    _offset = Offset.zero;
    _hasOverlay = false;
  }

  @override
  void dispose() {
    super.dispose();
    _commentController.dispose();
    _commentFocusNode1.dispose();
    _scrollController.dispose();
    _removeOverlay();
    _deatilsDataProvider.isFirst = false;
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    return GestureDetector(
      onTap: () {
        _removeOverlay();
      },
      child: Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          backgroundColor: Colors.white,
          iconTheme: IconThemeData(color: _shareProvider.textColor),
          elevation: 1,
          actions: <Widget>[
            IconButton(
              onPressed: () {},
              icon: Icon(
                Icons.more_horiz,
              ),
            ),
          ],
        ),
        body: _allDetails(_topDetails()),
      ),
    );
  }

  // 获取文章详情文章详情
  Widget _topDetails() {
    final CTYModel.Data itemData =
        _provider.allItem[widget.itemId]; // itemId对应的数据
    final Widget widgetItem = BuildArticleItem(
      textShowAll: false,
      showImages: _provider.showImages(widget.itemId),
      token: _shareProvider.token,
      isAttention: true,
      uid: _shareProvider.uid,
      isNextPage: false,
      provider: _provider,
      providerType: widget.providerType,
      itemData: itemData,
    );
    return widgetItem;
  }

  // 获取评论详情
  Widget _allDetails(Widget topDetails) {
    // 添加滚动条监听， 并把位置赋值给文章详情共享provider
    _addlistenOffset();
    return Container(
      child: Column(
        children: <Widget>[
          Expanded(
            child: _centent(topDetails),
          ),
          _bottomInput(),
        ],
      ),
    );
    // return _centent(topDetails);
  }

  // 底部输入框
  Widget _bottomInput() {
    return AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets, //边距（必要）
      duration: const Duration(milliseconds: 100), //时常 （必要,
      child: Row(
        children: <Widget>[
          _textInput(),
          _inputIcon(widget.itemId),
        ],
      ),
    );
  }

  // 输入框
  Widget _textInput() {
    return Expanded(
      child: TextField(
        autofocus: false,
        focusNode: _commentFocusNode1,
        controller: _commentController,
        keyboardType: TextInputType.text,
        cursorColor: _shareProvider.textColor,
        decoration: InputDecoration(
          hintText: "要不要留点什么。",
          border: null,
          contentPadding: EdgeInsets.only(
            left: Su().w(30),
            bottom: Su().h(5),
          ),
          focusedBorder: UnderlineInputBorder(
            //输入框被选中时的边框样式
            borderSide: BorderSide(color: _shareProvider.textColor),
          ),
        ),
      ),
    );
  }

  // 输入框右边的icon
  Widget _inputIcon(int rId) {
    return IconButton(
      icon: Icon(Icons.send),
      color: _shareProvider.textColor,
      onPressed: () async {
        String token = _shareProvider.token;
        String content = _commentController.text;
        int id = await CommentDetailsApi()
            .replyCommentsById(token, content, widget.itemId, -1);
        _deatilsDataProvider.deatilsData;
        CDModel.Data data = new CDModel.Data(
          _shareProvider.uid,
          _shareProvider.nickname,
          _shareProvider.headerImage,
          _shareProvider.sex == Sex.boy ? 1 : 2,
          id,
          content,
          (DateTime.now().millisecondsSinceEpoch) ~/ 1000,
          [],
        );
        _deatilsDataProvider.addDeatilsData(data, first: true);
        setState(() {});
        _commentFocusNode1.unfocus();
        _commentController.clear();
      },
    );
  }

  // 滚动条监听初始化
  void _addlistenOffset() {
    _scrollController =
        ScrollController(initialScrollOffset: _deatilsDataProvider.offset);
    _scrollController.addListener(() {
      _deatilsDataProvider.offset = _scrollController.offset;
      _removeOverlay();
    });
  }

  // 页面内容
  Widget _centent(Widget topDetails) {
    List<CDModel.Data> idComment = _deatilsDataProvider.deatilsData;
    return EasyRefresh.custom(
      header: SpaceHeader(),
      scrollController: _scrollController,
      controller: _easyRefreshController,
      firstRefresh: _deatilsDataProvider.isFirst,
      bottomBouncing: true,
      enableControlFinishLoad: true,
      onRefresh: () async {
        // 触发下拉加载
        _deatilsDataProvider.clean();
        setState(() {});
        _onLoad();
      },
      onLoad: () async {
        // 触发上拉加载
        await _onLoad();
        _deatilsDataProvider.isFirst = false;
      },
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildListDelegate(
            [
              topDetails,
            ],
          ),
        ),
        _sliver(idComment),
      ],
    );
  }

  // 页面的slivers
  Widget _sliver(List<CDModel.Data> idComment) {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          // 将评论展示出来
          CDModel.Data data = idComment[index];
          return _buildItem(data);
        },
        childCount: idComment.length,
      ),
    );
  }

  // 上拉加载
  Future<void> _onLoad() async {
    if (_deatilsDataProvider.isEndPage == false) {
      int page = _deatilsDataProvider.page;
      CommentDetailstModel commentDetailstModel = await CommentDetailsApi()
          .getAllCommentDetailsByItemId(_shareProvider.token, widget.itemId,
              page: page);
      if (commentDetailstModel.data.isEmpty == true) {
        _deatilsDataProvider.isEndPage = true;
        _easyRefreshController.finishLoad(success: true, noMore: true);
      } else {
        _deatilsDataProvider.page++;
        commentDetailstModel.data.forEach((item) {
          _deatilsDataProvider.addDeatilsData(item);
        });
        _easyRefreshController.finishLoad(success: true, noMore: false);
        setState(() {});
      }
    } else {
      _easyRefreshController.finishLoad(success: true, noMore: true);
    }
  }

  // 根据数据生成每一个widget
  Widget _buildItem(CDModel.Data commentData) {
    return Container(
      margin: EdgeInsets.only(
        top: Su().h(3),
      ),
      padding: EdgeInsets.only(
        bottom: Su().h(20),
      ),
      width: Su().w(750),
      color: Colors.white,
      child: Column(
        children: <Widget>[
          _userInfoTop(commentData),
          _firstComment(
              commentData.content, commentData.cId, commentData.userId),
          _sceondComment(commentData),
        ],
      ),
    );
  }

  // 评论信息
  Widget _userInfoTop(CDModel.Data commentData) {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          _userInfoHeaderImage(commentData.headImg),
          _userInfoNameAndDate(commentData),
        ],
      ),
    );
  }

  // 头像
  Widget _userInfoHeaderImage(String iamgeUrl) {
    return Container(
      padding: EdgeInsets.only(
        top: Su().h(21),
        left: Su().w(22),
      ),
      child: ClipOval(
        child: Image.network(
          iamgeUrl,
          width: Su().w(60),
          height: Su().w(60),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  // 时间和名字
  Widget _userInfoNameAndDate(CDModel.Data commentData) {
    Color color = _getTxetColorBySex(commentData.sex);
    return Container(
      padding: EdgeInsets.only(
        left: Su().w(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            commentData.nickName,
            style: Su().textStyle(color, 26),
          ),
          Text(
            Su().getDate(commentData.commentTime.toString()),
            style: Su().textStyle(Color.fromRGBO(179, 179, 179, 1), 20),
          ),
        ],
      ),
    );
  }

  // 通过性别获取不同颜色
  Color _getTxetColorBySex(int intSex) {
    Color gildColor = Color.fromRGBO(238, 135, 176, 1);
    Color boyColor = Color.fromRGBO(125, 207, 249, 1);

    Sex sex = IntToSex.getSex(intSex);
    Color color = sex == Sex.boy ? boyColor : gildColor;
    return color;
  }

  // 一级评论
  Widget _firstComment(String content, int cId, int userId) {
    return Container(
      margin: EdgeInsets.only(
        left: Su().w(92),
      ),
      padding: EdgeInsets.only(
        bottom: Su().h(18),
      ),
      width: Su().w(656),
      alignment: Alignment.centerLeft,
      child: GestureDetector(
        onTap: () async {
          if (userId == _shareProvider.uid) {
            _removeOverlay();
            _onLong(userId, content, cId);
          } else {
            _removeOverlay();
            await _show(cId);
          }
        },
        onLongPress: () {
          _removeOverlay();
          _onLong(userId, content, cId);
        },
        onPanDown: (DragDownDetails details) {
          _offset = details.globalPosition;
        },
        child: Text(
          content,
          style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 28),
        ),
      ),
    );
  }

  // 二级评论
  Widget _sceondComment(CDModel.Data commentData) {
    List<Widget> listWidget = [];
    if (commentData.replies.isEmpty == false) {
      commentData.replies.forEach((item) {
        listWidget.add(_everySecondComent(item, commentData.cId));
      });
    }
    return Column(
      children: listWidget,
    );
  }

  // 每一条二级评论
  Widget _everySecondComent(CDModel.Replies item, int cId) {
    double textSize = 26.0;
    return GestureDetector(
      onTap: () async {
        _removeOverlay();
        // rId就是当前的记录的id
        if (item.user.userId == _shareProvider.uid) {
          _removeOverlay();
          _onLong(item.user.userId, item.content, item.rId);
        } else {
          await _show(item.rId, firstId: cId, toUSer: item.toUser);
        }
      },
      onLongPress: () {
        _removeOverlay();
        _onLong(item.user.userId, item.content, item.rId);
      },
      onPanDown: (DragDownDetails details) {
        _offset = details.globalPosition;
      },
      child: Container(
        margin: EdgeInsets.only(
          left: Su().w(92),
          right: Su().w(40),
        ),
        width: Su().w(616),
        alignment: Alignment.centerLeft,
        child: Text.rich(
          TextSpan(children: [
            TextSpan(
              text: item.user.nickName,
              style:
                  Su().textStyle(_getTxetColorBySex(item.user.sex), textSize),
            ),
            TextSpan(
              text: "回复: ",
              style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), textSize),
            ),
            TextSpan(
              text: item.toUser.nickName,
              style:
                  Su().textStyle(_getTxetColorBySex(item.toUser.sex), textSize),
            ),
            TextSpan(
              text: item.content,
              style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), textSize),
            ),
          ]),
        ),
      ),
    );
  }

  // 底部弹出框
  Future<Widget> _show(int rId, {int firstId = -1, CDModel.To_user toUSer}) {
    return showModalBottomSheet(
      context: _context,
      builder: (BuildContext context) {
        return AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets, //边距（必要）
          duration: const Duration(milliseconds: 100), //时常 （必要,
          child: ShowCommunityInput(
            itemId: widget.itemId,
            rId: rId,
            providerType: widget.providerType,
            firstId: firstId,
            toUser: toUSer,
          ),
        );
      },
    );
  }

  // 自定义触发长按悬浮组件
  void _onLong(int userId, String content, int cId) {
    OverlayState overlayState = Overlay.of(context);
    //创建OverlayEntry
    _overlayEntry = OverlayEntry(builder: (BuildContext context) {
      return _onLongWidget(userId, content, cId);
    });
    //显示到屏幕上
    overlayState.insert(_overlayEntry);
    _hasOverlay = true;
  }

  // 悬浮组件
  Widget _onLongWidget(
    int userId,
    String content,
    int cId,
  ) {
    int uid = _shareProvider.uid;
    double width = Su().w(100);
    Widget widget = Container();
    if (uid == userId) {
      width = Su().w(200);
      widget = Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          _longCopy(content),
          _longDelete(cId),
        ],
      );
    } else {
      widget = Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          _longCopy(content),
        ],
      );
    }
    return Positioned(
      top: _offset.dy,
      left: _offset.dx,
      child: Container(
        width: width,
        height: Su().h(60),
        color: Colors.black,
        child: widget,
      ),
    );
  }

  // 长按复制实现
  Widget _longCopy(String content) {
    return GestureDetector(
      child: Text(
        "复制",
        style: Su().textStyle(Colors.white, 30),
      ),
      onTap: () {
        try {
          ClipboardData data = new ClipboardData(text: content);
          Clipboard.setData(data);
          _removeOverlay();
        } catch (error) {}
      },
    );
  }

  // 长按删除实现
  Widget _longDelete(int cId) {
    return GestureDetector(
      child: Text(
        "删除",
        style: Su().textStyle(Colors.white, 30),
      ),
      onTap: () async {
        String token = _shareProvider.token;
        bool success = await CommentDetailsApi()
            .deleteCommentsById(token, widget.itemId, cId);
        _removeOverlay();
        if (success == true) {
          // _deatilsDataProvider.clean();
          _deatilsDataProvider.deleteByCId(cId);
          setState(() {});
        }
      },
    );
  }

  // 移除悬浮组件
  void _removeOverlay() {
    if (_hasOverlay == true) {
      _overlayEntry.remove();
      _hasOverlay = false;
    }
  }
}
